package com.concurrent.chapter4.concurrent07;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/*
 * BlockingQueue是一个接口，常用的实现类有LinkedBlockingQueue和ArrayBlockingQueue.
 * LinkedBlockingQueue的好处在于没有大小限制，队列容量非常大，所以执行execute()不会抛出异常，
 * 线程池中运行的现成的数量永远也不会超过corePoolSize的值，
 * 因为多余的线程被放入LinkedBlockingQueue队列中，keepAliveTime参数也就没有意义了。
 */
public class Run3_1 {
	public static void main(String[] args) throws InterruptedException {
		Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				try {
					System.out.println(Thread.currentThread().getName() + " run!" + System.currentTimeMillis());
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		int corePoolSize = 7;
		int maximumPoolSize = 8;
		int keepAliveTime = 5;
		TimeUnit unit = TimeUnit.SECONDS;
		//队列使用LinkedBlockingDeque类，如果线程数量>corePoolSize时将其余的任务放入队列中。
		//同一时间最多只能有7个线程执行。
		//使用LinkedBlockingDeque类时，maximumPoolSize参数被忽略
		LinkedBlockingDeque<Runnable> workQueue = new LinkedBlockingDeque<Runnable>();
		ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
		executor.execute(runnable);//1
		executor.execute(runnable);//2
		executor.execute(runnable);//3
		executor.execute(runnable);//4
		executor.execute(runnable);//5
		executor.execute(runnable);//6
		executor.execute(runnable);//7
		executor.execute(runnable);//8
		//executor.execute(runnable);//8
		Thread.sleep(300);
		System.out.println("A:" + executor.getCorePoolSize());//7
		System.out.println("A:" + executor.getPoolSize());//7
		System.out.println("A:" + executor.getQueue().size());//1
		Thread.sleep(10000);
		System.out.println("B:" + executor.getCorePoolSize());//7
		System.out.println("B:" + executor.getPoolSize());//7
		System.out.println("B:" + executor.getQueue().size());//0
		
	}
}
